<template>
	<view>
		<uni-card spacing="0" padding="0" @click="goDetail">
			<image :src="item.thumbnailUrl" style="height: 300rpx; width: 100%;" mode="aspectFill"></image>
			<view class="warehouse-info">
				<view class="top-title">
					<view class="title-left">
						<view class="title">{{ item.warehouseName }}</view>
						<view class="desc">
							<image src="../static/assets/source/source-item-source.png"></image> {{
								item.warehouseType.typeName }}
						</view>
					</view>
					<view class="title-right">
						<view class="price">￥{{ item.rentalPrice }}</view>
						<view class="unit">m²/天</view>
					</view>
				</view>
				<view class="address">
					<image src="../static/assets/source/source-item-local.png"></image>{{ item.address }}
				</view>
				<view class="area">
					<image src="../static/assets/source/source-item-area.png"></image>可招租面积：{{ item.areaSize }}㎡
				</view>
				<view class="tags">
					<customtag v-for="(tag, tIdx) in item.warehouseTags" :key="tIdx" :item="tag">

					</customtag>
				</view>
			</view>
			<view class="card-btns">
				<button class="sub-btn" @tap.stop="onReserve">预约看仓</button>
				<button class="btn" @tap.stop="onContact">联系客服</button>
			</view>
		</uni-card>
		
		<!-- 登录弹窗 -->
		<uni-popup ref="loginPopup" type="center" :mask-click="false">
			<view class="login-popup">
				<view class="popup-header">
					<text class="popup-title">登录提示</text>
					<view class="popup-close" @click="closeLoginPopup">×</view>
				</view>
				<view class="popup-content">
					<text class="popup-desc">预约看仓需要先登录，请先完成登录</text>
					<button 
						class="wx-login-btn" 
						open-type="getUserInfo"
						@getuserinfo="handleUserInfo"
					>
						微信登录
					</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import customtag from './customtag.vue';
import { API, config } from '@/utils/api.js'

export default {
	name: "warehourseItem",
	components: {
		customtag,
	},
	props: {
		item: {}
	},
	data() {
		return {
			isLoggedIn: false,
			userInfo: {},
			pendingAction: null // 待执行的操作
		}
	},
	onShow() {
		this.checkLoginStatus()
	},
	mounted() {
		this.checkLoginStatus()
	},
	methods: {
		// 检查登录状态
		checkLoginStatus() {
			const userInfo = uni.getStorageSync('userInfo')
			const token = uni.getStorageSync('user-token')
			console.log('userInfo', userInfo)
			console.log('token', token)
			if (userInfo && token) {

				this.isLoggedIn = true
				this.userInfo = JSON.parse(userInfo)
			} else {
				this.isLoggedIn = false
				this.userInfo = {}
			}
		},

		// 获取微信登录code
		getCode() {
			return new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success: (res) => {
						resolve(res);
					},
					fail: (err) => {
						reject(err);
					}
				})
			})
		},

		// 处理微信用户信息授权
		async handleUserInfo(e) {
			if (e.detail.errMsg !== 'getUserInfo:ok') {
				uni.showToast({
					title: '需要授权才能使用',
					icon: 'none'
				})
				return
			}

			try {
				// 获取微信登录code
				const codeRes = await this.getCode()

				// 发送登录请求
				const loginData = {
					code: codeRes.code,
					nickName: e.detail.userInfo.nickName,
					avatarUrl: e.detail.userInfo.avatarUrl,
					encryptedData: e.detail.encryptedData,
					iv: e.detail.iv
				}

				const result = await API.auth.wxLogin(loginData)

				// 保存登录信息
				if (result && result.token) {
					// 修复：token 直接保存，不需要 JSON.stringify
					uni.setStorageSync('user-token', result.token)
					uni.setStorageSync('userInfo', JSON.stringify(result.userInfo))

					this.isLoggedIn = true
					this.userInfo = result.userInfo
					// 关闭登录弹窗
					this.closeLoginPopup()

					uni.showToast({
						title: '登录成功',
						icon: 'success'
					})

					// 执行待执行的操作
					if (this.pendingAction) {
						this.executeAction(this.pendingAction)
						this.pendingAction = null
					}
				} else {
					throw new Error('登录接口返回数据异常')
				}

			} catch (error) {
				console.error('微信登录失败:', error)
				uni.showToast({
					title: '登录失败，请重试',
					icon: 'none'
				})
			}
		},

		// 执行操作
		executeAction(action) {
			switch (action) {
				case 'reserve':
					this.goToReserve()
					break
				case 'detail':
					this.goToDetail()
					break
				default:
					break
			}
		},

		// 打开登录弹窗
		openLoginPopup(action) {
			this.pendingAction = action
			this.$refs.loginPopup.open()
		},

		// 关闭登录弹窗
		closeLoginPopup() {
			this.$refs.loginPopup.close()
			this.pendingAction = null
		},

		onReserve() {
			console.log('=== 点击预约按钮 ===');
			this.checkLoginStatus()
			// 检查是否已登录
			if (!this.isLoggedIn) {
				this.openLoginPopup('reserve')
				return
			}

			// 已登录，直接跳转
			this.goToReserve()
		},

		// 跳转到预约页面
		goToReserve() {
					this.checkLoginStatus()

			if (!this.item?.warehouseName) {
				uni.showToast({ title: '无法获取仓库信息', icon: 'none' });
				return;
			}

			uni.navigateTo({ 
				url: '/pages/reserve/reserve?warehouseId=' + encodeURIComponent(this.item.warehouseId) 
			});
		},

		onContact() {
			console.log('=== 点击联系客服按钮 ===', this.item);
			uni.makePhoneCall({
				phoneNumber: '021-31575228'
			})
		},

		goDetail() {
			console.log('=== 点击详情 ===');
			
			// 检查是否已登录
			if (!this.isLoggedIn) {
				this.openLoginPopup('detail')
				return
			}

			// 已登录，直接跳转
			this.goToDetailPage()
		},

		// 跳转到详情页面
		goToDetailPage() {
			const id = this.item.id || this.item.warehouseId;
			if (!id) {
				uni.showToast({ title: '缺少仓库ID', icon: 'none' });
				return;
			}

			uni.navigateTo({
				url: '/pages/warehouse/warehouseDetail?id=' + encodeURIComponent(id)
			});
		}
	}
}
</script>

<style lang="less" scoped>
.uni-card {
	padding: 0rpx !important;

	:deep(.uni-card__content) {
		padding: 0rpx !important;
	}
}

.warehouse-info {
	padding: 20rpx;

	image {
		width: 40rpx;
		height: 40rpx;
		object-fit: cover;
		margin-right: 10rpx;
	}

	.top-title {
		justify-content: space-between;
		align-items: center;
		display: flex;
		margin-bottom: 10rpx;

		.title-left {
			.title {
				font-size: 30rpx;
				font-weight: bold;
				color: #3F3F3F;
				margin-bottom: 10rpx;
			}

			.desc {
				margin-top: 10rpx;
				display: flex;
				font-size: 28rpx;
				font-weight: 400;
				color: #535353FF;
				display: flex;
				align-items: center;

				image {
					width: 22rpx;
					height: 25rpx;
					object-fit: contain;
					margin-right: 10rpx;
				}
			}
		}

		.title-right {
			.price {
				font-size: 36rpx;
				font-weight: 600;
				color: #C6282B;
			}

			.unit {
				margin-top: 10rpx;
				font-size: 24rpx;
				font-weight: 400;
				color: #9CA3AF;
			}
		}
	}

	.address {
		margin-bottom: 10rpx;
		color: #535353FF;
		font-size: 28rpx;
		font-weight: 400;
		display: flex;
		align-items: center;

		image {
			width: 19rpx;
			height: 25rpx;
			object-fit: contain;
			margin-right: 10rpx;
		}
	}

	.area {
		margin-bottom: 10rpx;
		color: #535353FF;
		font-size: 28rpx;
		font-weight: 400;
		display: flex;
		align-items: center;

		image {
			width: 25rpx;
			height: 25rpx;
			object-fit: contain;
			margin-right: 10rpx;
		}
	}

	.tags {
		display: flex;
		flex-wrap: wrap;
		align-items: flex-start;
		color: #6B7280;
		font-size: 28rpx;
		font-weight: 400;
		gap: 10rpx;

		image {
			object-fit: contain;
			margin-right: 10rpx;
		}
	}
}

.card-btns {
	display: flex;
	gap: 20rpx;
	margin: 0rpx 20rpx 20rpx 20rpx;

	.btn,
	.sub-btn {
		width: 100%;
		border-radius: 10rpx;
		font-size: 28rpx;
		font-weight: 400;
		padding: 0;
		height: 80rpx;
		line-height: 80rpx;
		box-sizing: border-box;
	}

	/* 预约看仓：红底白字 */
	.sub-btn {
		background-color: #C6282B;
		color: #fff !important;
		border: 1px solid #C6282B !important;
	}

	/* 联系客服：白底红字 */
	.btn {
		background-color: #fff;
		color: #C6282B !important;
		border: 1px solid #C6282B !important;
	}
}

/* 登录弹窗样式 */
.login-popup {
	background: #fff;
	border-radius: 20rpx;
	width: 600rpx;
	max-height: 80vh;
	overflow: hidden;
}

.popup-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx 30rpx 20rpx 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.popup-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.popup-close {
	font-size: 40rpx;
	color: #999;
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
}

.popup-content {
	padding: 30rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.popup-desc {
	display: block;
	font-size: 28rpx;
	color: #666;
	text-align: center;
	margin-bottom: 30rpx;
	line-height: 1.5;
}

.wx-login-btn {
	background: #07c160;
	color: white;
	border: none;
	border-radius: 44rpx;
	height: 88rpx;
	width: 300rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
}

.wx-login-btn::after {
	border: none;
}
</style>